<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <!-- <router-link target="_blank" :to="{path:'/pdf/download',params:{id:'8'}}">
            <el-button type="primary">
              Click to download PDF
            </el-button>
        </router-link> -->
        <el-button @click="getDataList()">查询</el-button>
        <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <!-- <el-button type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button> -->
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <!-- <el-table-column
        prop="id"
        header-align="center"
        align="center"
        label="合同表 id">
      </el-table-column> -->
      <el-table-column
        prop="contractName"
        header-align="center"
        align="center"
        label="合同名称">
      </el-table-column>
      <el-table-column
        prop="contractNum"
        header-align="center"
        align="center"
        label="合同编号">
      </el-table-column>
      <el-table-column
        prop="firstParty"
        header-align="center"
        align="center"
        label="甲方">
      </el-table-column>
      <el-table-column
        prop="secondParty"
        header-align="center"
        align="center"
        label="乙方">
      </el-table-column>

      <el-table-column
        header-align="center"
        align="center"
        label="合同起止日期">
        <template slot-scope="scope">
          {{ contractDateRange(scope.row.startTime, scope.row.endTime) }}
          <!-- {{scope.row.startTime}} 到 {{scope.row.endTime}} -->
        </template>
      </el-table-column>

      <!-- <el-table-column
        prop="endTime"
        header-align="center"
        align="center"
        label="合同结束日期">
      </el-table-column> -->
      <el-table-column
        prop="contractPrice"
        header-align="center"
        align="center"
        label="合同金额（元）">
      </el-table-column>
      <el-table-column
        prop="contractType"
        header-align="center"
        align="center"
        label="合同状态   0：在库   1： 借出">
      </el-table-column>
      <el-table-column
        prop="contractDesc"
        header-align="center"
        align="center"
        label="合同简要描述">
      </el-table-column>
      <el-table-column
        prop="paymentProgress"
        header-align="center"
        align="center"
        label="付款进度">
      </el-table-column>
      <el-table-column
        prop="storageLocation"
        header-align="center"
        align="center"
        label="合同存放位置">
      </el-table-column>
      <el-table-column
        prop="signingTime"
        header-align="center"
        align="center"
        label="合同签订日期">

        <template slot-scope="scope">
          {{ myFormatDate(scope.row.signingTime) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="inputPerson"
        header-align="center"
        align="center"
        label="录入人">
      </el-table-column>
      <el-table-column
        prop="inputTime"
        header-align="center"
        align="center"
        label="合同录入时间">

        <template slot-scope="scope">
          {{ myFormatDate(scope.row.inputTime) }}
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="borrowing(scope.row.id)">借阅</el-button>
          <!-- <el-button type="text" size="small" @click="showBorrowing(scope.row.id)">查询借阅记录</el-button> -->
          <el-button type="text" size="large" @click="dialogVisible = true">查询借阅记录</el-button>
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>

    <!-- 弹窗, 借阅 -->
    <!-- 合同的 id 传入到 子组件 -->
    <borrowing v-if="borrowingVisible" ref="borrowing" ></borrowing>

    <!-- 弹窗, 借阅记录 -->
    
    <!-- <BorrowingRecord v-if="borrowingRecordVisible" ref="borrowingRecord" ></BorrowingRecord> -->
    <!-- <BorrowingRecord v-if="borrowingRecordVisible" ref="borrowingRecord" ></BorrowingRecord> -->

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose">
      <span>这是一段信息</span>

      <BorrowingRecord ref="borrowingRecord" ></BorrowingRecord>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  // import axios from 'axios'

  import AddOrUpdate from './schoolcontract-add-or-update'
  import Borrowing from './contractborrowing-add-or-update.vue'
  import BorrowingRecord from './contractborrowing'

  export default {
    data () {
      return {
        dialogVisible: false,
        dataForm: {
          key: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        borrowingVisible: false,
        borrowingRecordVisible: false
      }
    },
    components: {
      AddOrUpdate,
      Borrowing,
      BorrowingRecord
    },
    mounted () {
      // 清空条件
      this.dataForm.key = ''
      this.dataList = []
      this.pageIndex = 1
      this.pageSize = 10

      this.getDataList()
    },
    computed: {
      
    },
    methods: {
      contractDateRange(start, end){
        // console.log(start, end)
        return this.getDateStr(start) + ' 到 ' + this.getDateStr(end)
      },

      getDateStr(time){
        var date = new Date(time);

        var year = date.getFullYear(),
          month = date.getMonth() + 1,//月份是从0开始的
          day = date.getDate()

        var newTime = year + '-' +
              month + '-' +
              day;
        return newTime;			
      },

      myFormatDate(time){
        var date = new Date(time);

        var year = date.getFullYear(),
          month = date.getMonth() + 1,//月份是从0开始的
          day = date.getDate(),
          hour = date.getHours(),
          min = date.getMinutes(),
          sec = date.getSeconds();
        var newTime = year + '-' +
              month + '-' +
              day + ' ' +
              hour + ':' +
              min + ':' +
              sec;
        return newTime;			
      },
      handleClose() {
        // this.$confirm('确认关闭？')
        //   .then(_ => {
        //     done();
        //   })
        //   .catch(_ => {});
      },

      // 获取数据列表
      getDataList () {
        

        this.dataListLoading = true

      //   this.$http({
      //   url: this.$http.adornUrl("/contract/contract/list"),
      //   method: "get",
      //   params: this.$http.adornParams({
      //     page: this.pageIndex,
      //     limit: this.pageSize,
      //     key: this.dataForm.key,
      //   }),
      // }).then(({ data }) => {
      //   if (data && data.code === 0) {
      //     this.dataList = data.page.list;
      //     this.totalPage = data.page.totalCount;
      //   } else {
      //     this.dataList = [];
      //     this.totalPage = 0;
      //   }
      //   this.dataListLoading = false;
      // });
      
      // this.$axios.get(`/contract/schoolcontract/list`
      this.$axios.get(`/contract/schoolcontract/list?key=${this.dataForm.key}&page=${this.pageIndex}&limit=${this.pageSize}`)
        .then(({ data }) => {
          // data = data.data
          console.log("获取到了数据",data);

          if (data && data.code === 0) {
            this.dataList = data.page.list;
            console.log("获取到的数据列表",this.dataList);
            this.totalPage = data.page.totalCount;
          } else {
            this.dataList = [];
            this.totalPage = 0;
          }
          this.dataListLoading = false;
          console.log("数据填充结束");
        })
        .catch(function (error) {
          console.log(error);
        });
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },

      // 借阅
      // 传入合同的 id ，保存到借阅记录表 contractId 字段 ，实体类 标注了 @TableId
      borrowing (id) {
        this.borrowingVisible = true
        this.$nextTick(() => {
          this.$refs.borrowing.init(id)
        })
      },

      // 显示借阅记录
      showBorrowing () {
        this.borrowingRecordVisible = true
        // this.$nextTick(() => {
        //   this.$refs.borrowingRecord.init(id)
        // })
      },

      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log("删除合同的 id 是",id)

          this.$axios.post(`http://localhost:10001/contract/schoolcontract/delete`, [id])
          .then(({ data }) => {
            // data = data.data
            console.log("删除了数据",data);
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          
          })
          .catch(function (error) {
            console.log(error);
          });

          // this.$http({
          //   url: this.$http.adornUrl('/contract/schoolcontract/delete'),
          //   method: 'post',
          //   data: this.$http.adornData(ids, false)
          // }).then(({data}) => {
          //   if (data && data.code === 0) {
          //     this.$message({
          //       message: '操作成功',
          //       type: 'success',
          //       duration: 1500,
          //       onClose: () => {
          //         this.getDataList()
          //       }
          //     })
          //   } else {
          //     this.$message.error(data.msg)
          //   }
          // })
        })
      }
    }
  }
</script>
